<?php
require_once dirname(__FILE__) . '/../../bootstrap.unit.php';
require_once FORAGE_APP_PATH . '/engine/xapian/XapianEngine.php';

class ForageXapianRealEngineTest extends ForageUnitTestCase
{
  private $path;
  private $config;
  private $xapian;

  public function setUp()
  {
    $this->path   = '/var/xapian/test';
    $this->config = array();
    $this->createForage();
  }

  public function tearDown()
  {
    unset($this->xapian, $this->config);
    shell_exec('rm -rf ' . $this->path);
  }

  public function createForage()
  {
    $this->xapian = Forage::create('xapian:' . $this->path, $this->config);
  }

  public function addDocs($count)
  {
    for ($i=1; $i<=$count; $i++) {
      $this->xapian->add($this->createDocument($i));
    }
  }

  public function createDocument($num=1)
  {
    switch ($num) {
    case 1:
      $name = 'first';
      break;
    case 2:
      $name = 'second';
      break;
    default:
      throw new Exception();
    }
    $document = new ForageDocument();
    $document->add('uid', (string)$num, array('uid'=>true))
             ->add('title', 'the '.$name.' document')
             ->add('body', 'this is the '.$name.' document', array('stored'=>false));
    return $document;
  }

  public function testAddingSimpleDocument()
  {
    $this->xapian->add($this->createDocument());
    $this->xapian->flush();
    $results = $this->xapian->search('first');
    $this->assertEquals(1, $results->total);
  }

  public function testStopwordRemoval()
  {
    $this->addDocs(2);
    $this->xapian->flush();
    $results = $this->xapian->search('the first');
    $this->assertEquals(2, $results->total);

    $this->config['stop_words'] = array('the');
    $this->createForage();
    $this->addDocs(2);
    $this->xapian->flush();
    $results = $this->xapian->search('the first');
    $this->assertEquals(1, $results->total);
  }

  public function testStemming()
  {
    $this->addDocs(2);
    $this->xapian->flush();
    $results = $this->xapian->search('documentation');
    $this->assertEquals(2, $results->total);

    $this->config['stemmer'] = false;
    $this->createForage();
    $this->addDocs(2);
    $this->xapian->flush();
    $results = $this->xapian->search('documentation');
    $this->assertEquals(0, $results->total);
  }

  public function testSynonyms()
  {
    $this->addDocs(2);
    $this->xapian->flush();
    $results = $this->xapian->search('page');
    $this->assertEquals(0, $results->total);

    $this->config['synonyms'] = array(
      'page' => array('document')
    );
    $this->createForage();
    $this->addDocs(2);
    $this->xapian->flush();
    $results = $this->xapian->search('page');
    $this->assertEquals(2, $results->total);
  }
}
